package com.lagou.edu.service;

import com.lagou.edu.dao.TokenDao;
import com.lagou.edu.model.Token;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;

import java.util.Optional;
import java.util.UUID;

@Service
public class TokenService implements ITokenService {

    @Autowired
    private TokenDao tokenDao;

    @Override
    public int register(String email, String password, String code) {
        if(isRegistered(email)){
            return -2;
        }
        Token token = new Token();
        token.setEmail(email);
        token.setToken(UUID.randomUUID().toString());
        tokenDao.save(token);
        return 0;
    }

    @Override
    public boolean isRegistered(String email) {
        Token token = new Token();
        token.setEmail(email);
        Example example = Example.of(token);
        Optional optional = tokenDao.findOne(example);
        return optional.isEmpty() ? false : true;
    }

    @Override
    public Token login(String email, String password) {
        Token token = new Token();
        token.setEmail(email);
        Example example = Example.of(token);
        Optional optional = tokenDao.findOne(example);
        return optional.isEmpty() ? null : (Token) optional.get();
    }

    @Override
    public Token findOneByToken(String token) {
        Token tokenModel = new Token();
        tokenModel.setToken(token);
        Example example = Example.of(tokenModel);
        Optional optional = tokenDao.findOne(example);
        return optional.isEmpty() ? null : (Token) optional.get();
    }
}